package com.xuecheng.framework.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: gongfy
 * @create: 2020/8/20 10:12
 * @Description:
 */
public class SysUtil {

    private static int seq = 1;
    private static final int ROTATION = 999999999;
    private static final Logger logger = LoggerFactory.getLogger(SysUtil.class);
    private static Map acctsystypeCache = new HashMap();

    public SysUtil() {
    }

    public static Map<String, String> convertStringToMap(String context, String separate, String connect) {
        if (context != null && !"".equals(context) && separate != null && !"".equals(separate) && connect != null && !"".equals(connect)) {
            Map<String, String> returnMap = new ConcurrentHashMap();
            String[] contextSep = context.split(separate);
            String[] contextSplit = null;
            String[] var6 = contextSep;
            int var7 = contextSep.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                String contextCon = var6[var8];
                contextSplit = contextCon.split(connect);
                if (contextSplit.length != 2) {
                    return null;
                }

                returnMap.put(contextSplit[0], contextSplit[1]);
            }

            return returnMap;
        } else {
            return null;
        }
    }

    public static Map<String, List<Map<String, String>>> groupDatas(String key, List<? extends Map<String, String>> datas) {
        Map<String, List<Map<String, String>>> returnMap = new HashMap();
        Iterator var3 = datas.iterator();

        while(var3.hasNext()) {
            final Map<String, String> map = (Map)var3.next();
            if (returnMap.containsKey(map.get(key))) {
                ((List)returnMap.get(map.get(key))).add(map);
            } else {
                returnMap.put(map.get(key), new ArrayList<Map<String, String>>() {
                    {
                        this.add(map);
                    }
                });
            }
        }

        return returnMap;
    }

    public static List<Map<String, Object>> convertKeyCase(List<Map<String, Object>> srcList, boolean toUpperCase) {
        if (srcList != null && !srcList.isEmpty()) {
            List<Map<String, Object>> decList = new ArrayList();
            Map<String, Object> decMap = null;
            Iterator var4 = srcList.iterator();

            while(var4.hasNext()) {
                Map<String, Object> srcMap = (Map)var4.next();
                decMap = new HashMap();
                Iterator var6 = srcMap.keySet().iterator();

                while(var6.hasNext()) {
                    String key = (String)var6.next();
                    decMap.put(toUpperCase ? key.toUpperCase() : key.toLowerCase(), srcMap.get(key));
                }

                decList.add(decMap);
            }

            return decList;
        } else {
            return srcList;
        }
    }

    public static String inSql(String keyField, List<String> keyValues) {
        StringBuffer sb = new StringBuffer();
        if (isNullOrEmpty(keyValues)) {
            sb.append("(  ").append(keyField).append(" in ('')) ");
        } else {
            sb.append("(  ").append(keyField).append(" in ( ");

            for(int i = 0; i < keyValues.size(); ++i) {
                if (i % 1000 == 0 && i != 0) {
                    sb.deleteCharAt(sb.length() - 1);
                    sb.append(") or ").append(keyField).append(" in ( ");
                }

                sb.append("'").append((String)keyValues.get(i)).append("',");
            }

            sb.deleteCharAt(sb.length() - 1);
            sb.append(") )");
        }

        return sb.toString();
    }

    public static String inSqlByGemini(String keyField, List<String> keyValues) {
        StringBuffer sb = new StringBuffer();
        if (isNullOrEmpty(keyValues)) {
            sb.append("(  ").append(keyField).append(" in ( values (''))) ");
        } else {
            sb.append("(  ").append(keyField).append(" in ( values ");

            for(int i = 0; i < keyValues.size(); ++i) {
                sb.append("('").append((String)keyValues.get(i)).append("'),");
            }

            sb.deleteCharAt(sb.length() - 1);
            sb.append(") )");
        }

        return sb.toString();
    }

    public static String generateGuid() {
        return UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
    }

    public static void main(String[] args) {
        String id = generateGuid();
        System.out.println(id);
    }

    public static String generateNumber(int length, int max_no) {
        return String.format("%1$" + String.format("%1$02d", length) + "d", max_no);
    }

    public static synchronized String generateNumberByDate() {
        if (seq > 999999999) {
            seq = 1;
        }

        Date date = new Date();
        date.setTime(System.currentTimeMillis());
        return String.format("%1$tY%1$tm%1$td%1$tk%1$tM%1$tS%2$05d", date, seq++);
    }

    public static String generateShortUuid(int length) {
        if (length < 1) {
            return "";
        } else {
            StringBuffer shortBuffer = new StringBuffer();
            String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
            String uuid = UUID.randomUUID().toString().replace("-", "");

            for(int i = 0; i < length; ++i) {
                String str = uuid.substring(i * 4, i * 4 + 4);
                int x = Integer.parseInt(str, 16);
                shortBuffer.append(chars[x % 62]);
            }

            return shortBuffer.toString();
        }
    }

    public static String getDate(String format, int day) {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat formatDate = new SimpleDateFormat(format != null && !"".equals(format) ? format : "yyyy-MM-dd HH:mm:ss");
        c.add(5, day);
        return formatDate.format(c.getTime());
    }

    public static String convertStringToFormateDate(String dateString, String srcFormate, String desFormate) {
        try {
            return (new SimpleDateFormat(desFormate)).format((new SimpleDateFormat(srcFormate != null && !"".equals(srcFormate) ? srcFormate : "yyyy-MM-dd HH:mm:ss")).parse(dateString));
        } catch (ParseException var4) {
            var4.printStackTrace();
            return "";
        }
    }

    public static int getCurrentMonth() {
        Calendar c1 = Calendar.getInstance();
        Integer curentYear = c1.get(1);
        Integer sysyear = 2018;
        if (curentYear < sysyear) {
            return 1;
        } else {
            return curentYear > sysyear ? 12 : c1.get(2);
        }
    }

    public static String formatAMT(String amt, String format) {
        boolean isNegative = false;
        if (amt.startsWith("-")) {
            isNegative = true;
        }

        BigDecimal b = new BigDecimal(amt);
        DecimalFormat d1 = new DecimalFormat(format != null && !"".equals(format) ? format : "#,##0.00;(#)");
        return (isNegative ? "-" : "") + d1.format(b.abs());
    }

    public static String formatDate(String date, String srcFormat, String desFormat) {
        if (!StringUtils.isEmpty(date) && !StringUtils.isEmpty(desFormat)) {
            SimpleDateFormat ori = new SimpleDateFormat(srcFormat != null && !"".equals(srcFormat) ? srcFormat : "yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat dest = new SimpleDateFormat(desFormat);

            try {
                Date d = ori.parse(date);
                return dest.format(d);
            } catch (ParseException var6) {
                logger.error("格式化日期字段异常：" + var6.getMessage() + " " + ExceptionUtils.getStackTrace(var6));
                return date;
            }
        } else {
            return date;
        }
    }

    public static Object deepCope(Object obj) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bo);
        out.writeObject(obj);
        ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bo.toByteArray()));
        Object copyObj = input.readObject();
        return copyObj;
    }

    public static String nullConvert(String obj) {
        return obj == null ? "" : obj;
    }



    public static boolean isNullOrEmpty(String string) {
        return string == null || string.equals("") || string.equals("null");
    }

    public static boolean isNullOrEmpty(List list) {
        return list == null || list.size() == 0;
    }

    public static boolean isNullStr(Object s) {
        return s == null || s.toString().length() <= 0;
    }

    public static boolean isNullOrEmpty(Map map) {
        return map == null || map.isEmpty();
    }

    public static String nonNullStr(Object o) {
        return nonNullStr(o, "");
    }

    public static String nonNullStr(Object o, String def) {
        String s = o == null ? def : o.toString();
        if (s.equalsIgnoreCase("null") || s.equalsIgnoreCase("")) {
            s = def;
        }

        return s;
    }

    public static Map<String, Map> groupListDatas(List<Map> list, String key) {
        Map<String, Map> rtnMap = new HashMap();
        Iterator var3 = list.iterator();

        while(var3.hasNext()) {
            Map map = (Map)var3.next();
            String mapKey = nonNullStr(map.get(key));
            if (mapKey != null) {
                rtnMap.put(mapKey, map);
            }
        }

        return rtnMap;
    }

    public static String getListString(List<String> srclist) {
        if (isNullOrEmpty(srclist)) {
            return "";
        } else {
            StringBuffer stringBuffer = new StringBuffer();
            int i = 0;

            for(int n = srclist.size(); i < n; ++i) {
                stringBuffer.append((String)srclist.get(i)).append("#");
            }

            return stringBuffer.deleteCharAt(stringBuffer.length() - 1).toString();
        }
    }

    public static String getSql(String tab_name, Object[] selectCol, Object[] params, Object[] orderbys) {
        StringBuffer sql = new StringBuffer();
        sql.append("select ");
        if (selectCol == null) {
            sql.append("* ");
        } else {
            sql.append(getParamSql((String)null, selectCol, ",", true));
        }

        sql.append("from ").append(tab_name);
        if (params != null) {
            sql.append(" where ").append(getParamSql((String)null, params, "and", false));
        }

        if (orderbys != null) {
            sql.append(" order by ").append(getParamSql((String)null, orderbys, ",", true));
        }

        return sql.toString();
    }

    public static String getParamSql(String alia, Object[] param, String splitAlia, boolean isSelect) {
        StringBuffer sql = new StringBuffer();

        for(int i = 0; i < param.length; ++i) {
            if (i == param.length - 1) {
                sql.append(alia != null && !alia.equals("") ? alia + "." : "").append(param[i]).append(isSelect ? " " : " =? ");
            } else {
                sql.append(alia != null && !alia.equals("") ? alia + "." : "").append(param[i]).append(isSelect ? " " : " =? ").append(splitAlia).append(" ");
            }
        }

        return sql.toString();
    }


    public static String boxUpSql(String sql) {
        StringBuffer sb = new StringBuffer();
        sb.append("select * from ( select row_.*, rownum rownum_ from ( ");
        sb.append(sql);
        sb.append(" ) row_ where rownum <= ?) where rownum_ > ?");
        return sb.toString();
    }

    public static String getAcctSysType() {
        return null;
    }

    public static void setAcctsystype(String acctsystype) {
    }

    public static String getCacheKey(String field, Integer year, String province) {
        return field + "#" + year + "#" + province;
    }

    public static String getDepartmentCacheKey(String guid, Integer year, String province) {
        return "department#" + year + "#" + province + "#" + guid;
    }

    public static String[] breakCacheKey(String key) {
        String[] keyStrings = key.split("#");
        return keyStrings;
    }

    public static String toStr(Object object) {
        if (object instanceof BigDecimal) {
            return ((BigDecimal)object).toString();
        } else {
            return object instanceof Object ? object.toString() : String.valueOf(object);
        }
    }

    public static Map<String, Map> groupDtoDatasByTwoKey(List<Map> list, String key1, String key2) {
        Map<String, Map> rtnMap = new HashMap();
        Iterator var4 = list.iterator();

        while(var4.hasNext()) {
            Map map = (Map)var4.next();
            if (map.get(key1) != null && map.get(key2) != null) {
                String mapKey = map.get(key1) + "#" + map.get(key2);
                if (!rtnMap.containsKey(mapKey)) {
                    rtnMap.put(mapKey, map);
                }
            }
        }

        return rtnMap;
    }

    public static String getCurrentTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }

    public static String getCurrentMs() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        return format.format(new Date());
    }

    public static String getCurrentDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
        return format.format(new Date());
    }

    public static String getCurrentDate(String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(new Date());
    }

    public static List buildTreeDatas(List list, String parentId) throws RuntimeException {
        if (!isNullOrEmpty(list) && list.size() != 1) {
            int size = list.size();
            Map<String, Integer> guidPos = new HashMap();
            Map<String, List<Map<String, Object>>> superMap = new HashMap();
            String guid = null;
            String superguid = null;
            List<Map<String, Object>> childList = null;
            Map<String, Object> m = null;

            for(int i = 0; i < size; ++i) {
                m = (Map)list.get(i);
                m.put("isleaf", "1");
                m.put("icon", "fa fa-file-text");
                guid = nonNullStr(m.get("guid"));
                superguid = nonNullStr(m.get("superguid"), "0");
                if (!m.containsKey("id")) {
                    m.put("id", guid);
                }

                guidPos.put(guid, i);
                if (superMap.containsKey(superguid)) {
                    childList = (List)superMap.get(superguid);
                } else {
                    childList = new ArrayList();
                    superMap.put(superguid, childList);
                }

                ((List)childList).add(m);
            }

            Set<String> keySet = superMap.keySet();
            List<Map<String, Object>> result = new ArrayList();
            Iterator var11 = keySet.iterator();

            while(var11.hasNext()) {
                String key = (String)var11.next();
                if (guidPos.containsKey(key)) {
                    m = (Map)list.get((Integer)guidPos.get(key));
                    m.put("isleaf", "0");
                    m.put("icon", "fa fa-folder");
                    m.put("children", superMap.get(key));
                } else {
                    result.addAll((Collection)superMap.get(key));
                }
            }

            if (result.size() == 1) {
                Map<String, Boolean> state = new HashMap();
                state.put("opened", true);
                m = (Map)result.get(0);
                m.put("state", state);
            }

            return result;
        } else {
            if (!isNullOrEmpty(list)) {
                Map<String, Object> m = (Map)list.get(0);
                if (!m.containsKey("id")) {
                    m.put("id", m.get("guid"));
                }

                m.put("isleaf", "1");
            }

            return list;
        }
    }

    public static boolean isNotNullStr(Object s) {
        return !isNullStr(s);
    }

    public static Map<String, Object> getMenuParam(String param5) {
        Map<String, Object> params = new HashMap();
        if (StringUtils.isEmpty(param5)) {
            return null;
        } else {
            param5 = param5.substring(0, param5.length() - 1).replace(" ", "");
            String[] paramArr = param5.split(",");
            String[] var3 = paramArr;
            int var4 = paramArr.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                String p = var3[var5];
                String[] obj = p.split("=");
                params.put(obj[0], obj[1]);
            }

            return params;
        }
    }


}
